package com.ouyeel.wlxer.api;

import com.ouyeel.wlxer.util.Config;
import com.ouyeel.wlxer.util.DeviceUtils;
import com.ouyeel.wlxer.util.MyApplication;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by rankaifeng on 2017/9/25.
 */

public class RetrofitClicent {
    private static RetrofitClicent instanse;

    public static RetrofitClicent getInstanse() {
        if (instanse == null) {
            instanse = new RetrofitClicent();
        }
        return instanse;
    }

    public <T> void toSubscribe(Observable<T> observable, Observer<T> observer) {
        observable.subscribeOn(Schedulers.io())    // 指定subscribe()发生在IO线程
                .observeOn(AndroidSchedulers.mainThread())  // 指定Subscriber的回调发生在io线程
                .subscribe(observer);   //订阅
    }

    public WlxerApi getRetrofit(Class type) {
        return new Retrofit.Builder()
                .baseUrl(Config.TEST_URL)
//                .addConverterFactory(new JsonConverterFactory(type))
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(getOkHttpClient())
                .build().create(WlxerApi.class);
    }

    private OkHttpClient getOkHttpClient() {
        return new OkHttpClient.Builder().addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request newRequest = chain.request().newBuilder()
                        .addHeader("appType", "10")
                        .addHeader("deviceId", DeviceUtils.getUniqueId(MyApplication
                                .getContextObject()))
                        .build();
                return chain.proceed(newRequest);
            }
        }).connectTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build();
    }
}
